package com.habitsoft.glassfish.dashboard.server;

import java.lang.management.ClassLoadingMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;

import javax.annotation.security.DeclareRoles;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.habitsoft.glassfish.dashboard.client.JvmStats;
import com.habitsoft.glassfish.dashboard.client.MemoryPoolInfo;
import com.habitsoft.glassfish.dashboard.client.StatService;

@DeclareRoles("stat-service")
public class StatServiceImpl extends RemoteServiceServlet implements StatService {
    private static final long serialVersionUID = 1L;

    @Override
    public JvmStats getJvmStats() {
        MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
        long heapSize = mem.getHeapMemoryUsage().getUsed();
        long maxHeapSize = mem.getHeapMemoryUsage().getMax();
        ThreadMXBean thread = ManagementFactory.getThreadMXBean();
        int threadCount = thread.getThreadCount();
        int daemonThreads = thread.getDaemonThreadCount();
        ClassLoadingMXBean classes = ManagementFactory.getClassLoadingMXBean();
        int loadedClassCount = classes.getLoadedClassCount();
        ArrayList<MemoryPoolInfo> memoryPools = new ArrayList<MemoryPoolInfo>();
        for (MemoryPoolMXBean mx : ManagementFactory.getMemoryPoolMXBeans()) {
            MemoryUsage usage = mx.getUsage();
            memoryPools.add(new MemoryPoolInfo(mx.getName(), usage.getMax(), usage.getUsed(), usage.getCommitted()));
        }
        memoryPools.add(new MemoryPoolInfo("Total Heap", maxHeapSize, heapSize, mem.getHeapMemoryUsage().getCommitted()));
        memoryPools.add(new MemoryPoolInfo("Total Non-Heap", mem.getNonHeapMemoryUsage().getMax(), mem.getNonHeapMemoryUsage().getUsed(), mem.getNonHeapMemoryUsage().getCommitted()));
        
        JvmStats stats = new JvmStats(maxHeapSize,
            heapSize,
            loadedClassCount,
            threadCount,
            daemonThreads,
            memoryPools.toArray(new MemoryPoolInfo[memoryPools.size()]));
        return stats;
    }
}
